<script lang='ts'  setup>
import { reactive, ref, nextTick } from 'vue';
import api from '@/api';
import { ElMessageBox, FormRules, ElMessage } from 'element-plus';
import * as icons from '@element-plus/icons-vue'

// 查询条件
const query = ref<{ menuName: string | undefined, menuState: number }>({ menuName: undefined, menuState: 1 })
// 查询表单的 ref
const queryFormRef = ref()
// 菜单数据列表
const menus = ref()
// 处理查询
const handleQuery = async () => {
    const { data: res } = await api.getMenuListApi(query.value)
    menus.value = res
}
handleQuery()

// 表格列
const columns = reactive<{ prop: string, label: string, formatter?: Function }[]>([
    { prop: 'menuName', label: '菜单名称' },
    { prop: 'icon', label: '图标' },
    { prop: 'menuType', label: '菜单类型', formatter(row: [], col: [], val: number) { return { 1: '菜单', 2: '按钮' }[val] } },
    { prop: 'permission', label: '权限标识' },
    { prop: 'path', label: '路由地址' },
    { prop: 'component', label: '组件路径' },
    { prop: 'menuState', label: '菜单状态', formatter(row: [], col: [], val: number) { return { 1: '正常', 2: '禁用' }[val] } },
    { prop: 'createTime', label: '创建时间', },
    { prop: 'updateTime', label: '最后更新时间', }
])


/**
 * dialog
 */

const dialogVisible = ref(false)
const editMode = ref(true)
const menuFormRef = ref()
const handleClose = () => {
    ElMessageBox.confirm(
        `确定退出${editMode ? '编辑' : '创建'}菜单吗？`,
        `${editMode ? '编辑' : '创建'}菜单`,
        {
            showClose: false,
            cancelButtonText: '取消',
            confirmButtonText: '确定',
        }
    )
        .then(() => {
            // done()
            dialogVisible.value = false
            menuFormRef.value.resetFields()
        })
        .catch(() => {
            // catch error
        })
}

// 菜单表单
const menuForm = ref<{
    parentId?: string[]
    menuType?: number
    menuName?: string
    icon?: string
    path?: string
    component?: string
    menuCode?: string
    menuState?: number
    parentDisabled?: boolean
}>({ menuType: 1, menuState: 1 })

// 菜单提交
const menuCommit = () => {
    menuFormRef.value.validate(async (isValid: boolean) => {
        if (isValid) {
            try {
                await api.menuOper(menuForm.value, editMode.value ? 'put' : 'post')
                ElMessage.success(`成功${editMode.value ? '修改' : '创建'}菜单`)
                dialogVisible.value = false
                menuFormRef.value.resetFields()
                handleQuery()
            } catch (error) {
                ElMessage.error(`操作失败：${error}`)
            }
        }
    })
}

// 行操作
const handleRowOper = async (row: any, type: number = 1) => {
    // number: 1:增加 2: 修改 3:删除
    if (type === 1) {
        editMode.value = false
        dialogVisible.value = true
        menuForm.value.parentId = [JSON.parse(JSON.stringify(row))._id]
        menuForm.value.parentDisabled = true
    } else if (type === 2) {
        editMode.value = dialogVisible.value = true
        nextTick(() => {
            menuForm.value = JSON.parse(JSON.stringify(row))
        })
    } else if (type === 3) {
        try {
            ElMessageBox.confirm('确认删除此菜单吗？', '提示', {
                showClose: false,
                cancelButtonText: '取消',
                confirmButtonText: '确定'
            })
                .then(async () => {
                    await api.menuOper({ _id: row._id }, 'delete')
                    handleQuery()
                    ElMessage.success('菜单删除成功')
                }).catch(() => { })

        } catch (error) {
            ElMessage.error('菜单删除失败')
        }
    }
}


// 菜单表单 验证规则 
const menuFormRules = reactive<FormRules>({
    menuName: [
        { required: true, message: '请输入菜单名称', trigger: 'blur' },
        { min: 2, max: 10, message: '菜单名称的长度限制为2~10', trigger: 'blur' }
    ],
    path: [
        { pattern: /^[\/].*$/, message: '路由地址不合法', trigger: 'blur' }
    ]
})


</script>

<template>
    <div id='MenuManage'>
        <div class=" p-[20px] pb-0   card overflow-hidden ">
            <!-- 条件查询表单区域 -->
            <el-form inline :model="query" ref="queryFormRef">
                <el-form-item label="菜单名称" prop="menuName">
                    <el-input placeholder="请输入菜单名称" v-model.trim="query.menuName" />
                </el-form-item>
                <el-form-item label="状态" prop="menuType">
                    <el-select v-model="query.menuState">
                        <el-option :value="0" label="全部" />
                        <el-option :value="1" label="正常" />
                        <el-option :value="2" label="停用" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleQuery">查询</el-button>
                    <el-button type="danger" @click="queryFormRef.resetFields()">重置</el-button>
                </el-form-item>
            </el-form>

        </div>
        <div class=" h-[20px] bg-slate-50" />
        <div class=" card ">
            <!-- 操作区域 -->
            <div class=" p-[20px]">
                <el-button type="primary"
                    @click="editMode = false; dialogVisible = true; menuForm.parentDisabled = false">创建</el-button>
            </div>
            <!-- 表格正文 -->
            <el-table :data="menus" max-height="500px" row-key="_id" size="default">
                <!-- 循环渲染表格列 -->
                <el-table-column v-for="column in columns" :key="column.prop" :prop="column.prop" :label="column.label"
                    :formatter="column.formatter">
                    <!-- icon的插槽 -->
                    <template #default="scope" v-if="column.prop === 'icon'">
                        <el-icon v-if="scope.row.icon">
                            <component :is="scope.row.icon" />
                        </el-icon>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="120px" fixed="right">
                    <template #default="scope">
                        <div class="flex justify-end">
                            <el-tooltip effect="dark" :hide-after="0" :enterable="false" content="增加菜单"
                                v-if="scope.row.menuType == 1" placement="bottom-start">
                                <el-button type="primary" circle @click="handleRowOper(scope.row, 1)">+</el-button>
                            </el-tooltip>
                            <el-tooltip effect="dark" :hide-after="0" :enterable="false" content="编辑菜单"
                                placement="bottom">
                                <el-button type="primary" icon="Edit" circle @click="handleRowOper(scope.row, 2)" />
                            </el-tooltip>
                            <el-tooltip effect="dark" :hide-after="0" :enterable="false" content="删除菜单"
                                placement="bottom-end">
                                <el-button type="danger" icon="Delete" circle @click="handleRowOper(scope.row, 3)" />
                            </el-tooltip>
                        </div>
                    </template>
                </el-table-column>
            </el-table>

            <!-- dialog -->

            <el-dialog v-model="dialogVisible" :title="`${editMode ? '编辑' : '创建'}菜单`" width="30%"
                :before-close="handleClose" :show-close="false">

                <el-form size="default" :model="menuForm" label-width="auto" :rules="menuFormRules" ref="menuFormRef">
                    <!-- TODO 过滤按钮选项 -->
                    <el-form-item label="父级菜单" prop="parentId">
                        <el-cascader :options="menus" v-model="menuForm.parentId" placeholder="请选择父级菜单" clearable
                            :disabled="menuForm.parentDisabled" class=" w-[70%]" :props="{
                                checkStrictly: true,
                                label: 'menuName',
                                value: '_id',
                            }" />
                        <el-icon class="mx-[10px]">
                            <Warning />
                        </el-icon>
                        <span class="text-[12px] text-gray-400">未选则生成一级菜单</span>
                    </el-form-item>
                    <el-form-item label="菜单类型" prop="menuType">
                        <el-radio-group v-model="menuForm.menuType">
                            <el-radio :label="1">菜单</el-radio>
                            <el-radio :label="2">按钮</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="菜单名称" prop="menuName">
                        <el-input v-model.trim="menuForm.menuName" />
                    </el-form-item>
                    <el-form-item label="权限标识" prop="menuCode" v-show="menuForm.menuType === 2">
                        <el-input v-model="menuForm.menuCode" />
                    </el-form-item>
                    <el-form-item label="菜单图标" prop="icon" v-show="menuForm.menuType === 1">
                        <el-select v-model="menuForm.icon" clearable placeholder="请选择图标" filterable>
                            <el-option v-for="icon in icons" :value="icon.name" :label="icon.name" :key="icon.name">
                                <template #default>
                                    <div class="flex items-center">
                                        <el-icon>
                                            <component :is="icon" />
                                        </el-icon>
                                        <span class="pl-[10px] text-[12px] text-gray-400">{{ icon.name }}</span>
                                    </div>
                                </template>
                            </el-option>
                        </el-select>
                        <div class="flex items-center">
                            <el-icon class="mx-[10px]">
                                <Warning />
                            </el-icon>
                            <span class="text-[12px] text-gray-400">可以输入搜索图标</span>
                        </div>

                    </el-form-item>
                    <el-form-item label="路由地址" prop="path" v-show="menuForm.menuType === 1">
                        <el-input v-model.trim="menuForm.path" />
                    </el-form-item>
                    <el-form-item label="组件路径" prop="component" v-show="menuForm.menuType === 1">
                        <el-input v-model.trim="menuForm.component" />
                    </el-form-item>
                    <el-form-item label="菜单状态" prop="menuState" v-show="menuForm.menuType === 1">
                        <el-radio-group v-model="menuForm.menuState">
                            <el-radio :label="1">正常</el-radio>
                            <el-radio :label="2">停用</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-form>


                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="handleClose" size="default">取消</el-button>
                        <el-button type="primary" @click="menuCommit" size="default">{{ editMode ? '保存' :
                                '创建'
                        }}
                        </el-button>
                    </span>
                </template>
            </el-dialog>
        </div>
    </div>
</template>